package week_1.practice;
import java.util.Iterator;
import java.util.Stack;


public class LinkedStack<T> implements StackADT<T> {
    //在栈中储存元素的数量。
    private int count;
    //指向栈顶的指针。
    private LinearNode<T> top;

    public LinkedStack(){
        count = 0;
        top = null;
    }
/*Adds the specified element to the top of this stack.
* @param element element to be pushed on stack*/
    @Override//链表的插入。
    public void push(T element) {
        LinearNode<T> temp = new LinearNode<T>(element);

        temp.setNext(top);//同temp.next=top;一样
        top = temp;
        count++;
    }
/*Removes the element at the top of this stack and returns a
* reference to it.Throws an EmptyCollectionException if the stack
* is Empty.
* @return T element from top of stack
* @throw EmptyCollection on pop from empty stack*/
    @Override
    public T pop() throws EmptyCollectionException
    {
       if(isEmpty())
           throw new EmptyCollectionException("Stack");

       T result = top.getElement();
       top = top.getNext();
       count--;

        return result;
    }

    @Override
    public T peek() throws EmptyCollectionException{
        if(isEmpty())
            throw new EmptyCollectionException("Stack");

        T result = top.getElement();
        return result;
    }

    @Override
    public boolean isEmpty() {
        if(size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public int size() {
        return count;
    }


    //遍历链表实现toString方法。
    public  String toString(){
       LinearNode<T> temp;
       temp = top;
       String result ="";
       while(temp!=null){
           result += temp.getElement()+"\t";
           temp=temp.getNext();
       }
        return result;
    }
}
